﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cinchoo.Core.ETL;
using Cinchoo.Core;
using Cinchoo.Core.IO;
using System.IO;

namespace RSPETLTasks
{
    /// <summary>
    /// Task to monitor process. If 
    /// </summary>
    public class RPSFtpGetTask : ChoETLJob
    {
        #region Instance Data Members (Private)

        private readonly string _requestUriString;
        private readonly string _destinationFilePath;

        #endregion Instance Data Members (Private)

        #region Instance Properties

        public string UserName
        {
            get;
            set;
        }

        public string Password
        {
            get;
            set;
        }


        #endregion Instance Properties

        public RPSFtpGetTask(string requestUriString, string destinationFilePath = null)
        {
            ChoGuard.ArgumentNotNullOrEmpty(requestUriString, "RequestUriString");

            _requestUriString = requestUriString;
            if (destinationFilePath.IsNullOrWhiteSpace())
                _destinationFilePath = ChoPath.GetFullPath(new Uri(requestUriString).AbsolutePath);
            else
                _destinationFilePath = destinationFilePath;
        }

        protected override void ExecuteTask()
        {
            //CREATE AN FTP REQUEST WITH THE DOMAIN AND CREDENTIALS
            System.Net.FtpWebRequest tmpReq = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(_requestUriString);
            if (!UserName.IsNullOrWhiteSpace())
                tmpReq.Credentials = new System.Net.NetworkCredential("userName", "Password");

            string line = null;
            //GET THE FTP RESPONSE
            using (System.Net.WebResponse tmpRes = tmpReq.GetResponse())
            {
                //GET THE STREAM TO READ THE RESPONSE FROM
                using (System.IO.Stream tmpStream = tmpRes.GetResponseStream())
                {
                    //CREATE A TXT READER (COULD BE BINARY OR ANY OTHER TYPE YOU NEED)
                    using (System.IO.TextReader tmpReader = new System.IO.StreamReader(tmpStream))
                    {
                        while ((line = tmpReader.ReadLine()) != null)
                        {
                            //STORE THE FILE CONTENTS INTO A STRING
                            //using (FileStream sw = File.OpenWrite(_destinationFilePath))
                            //    sw.Wr(line);
                        }
                        string fileContents = tmpReader.ReadToEnd();

                        //DO SOMETHING WITH SAID FILE CONTENTS
                    }
                }
            }
        }
    }
}
